<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>增删改查</title>
    <style>
        div {
            width: 100px;
            height: 100px;
            border: 1px solid #000;
        }

        #d1 {
            background: red;
        }

        #d2 {
            background: blue;
        }

        #d3 {
            background: purple;
        }

        #d4 {
            background: pink;
        }
    </style>
</head>
<body>
    <button onclick="addNode()">增加</button>
    <button onclick="removeNode()">删除</button>
    <button onclick="replaceNode()">替换</button>
    <button onclick="copyNode()">克隆</button>
    <hr>
   <div id="d1">
        d1
    </div>
    <div id="d2">
        d2
    </div>
    <div id="d3">
        d3
        <p>
            这是一个段落
        </p>
    </div>
    <div id="d4">
        d4
    </div>
</body>
    <script>
        function copyNode(){
            var obj3 = document.getElementById("d3")
            var objnew = obj3.cloneNode(true)
            var objParent = obj3.parentNode
            var obj2 = document.getElementById("d2")
            objParent.insertBefore(objnew,obj2)
        }
        function replaceNode(){
            var objH1 = document.createElement("h1")
            objH1.innerHTML = "我是一个标题"
            var objOld = document.getElementById("d1")
            var objpent = objOld.parentNode
            objpent.replaceChild(objH1,objOld)
        }
        function removeNode(){
            var objBody = document.body
            objDiv = document.getElementsByTagName("div")
            objBody.removeChild(objDiv[objDiv.length-1])
        }
        function addNode(){
            var objBody = document.getElementsByTagName("body")[0]

            var objDiv = document.createElement("div")
            objDiv.innerHTML = "李伟聪，很帅"

            objDiv.style.width = "150px"
            objDiv.style.height = "150px"
            var r = Math.floor(Math.random()*255)
            var g = Math.floor(Math.random()*255)
            var b = Math.floor(Math.random()*255)
            objDiv.style.background = "rgb("+r+","+g+","+b+")"
            objBody.appendChild(objDiv)
        }
    </script>
</html>